#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#include <WinSock2.h>
#include <string>
#include <cstring>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
uint16_t serverPort = 8888;
string serverIp = "1.12.56.171"; // 你的云服务器IP
#define NUM 1024
int main()
{
    WSAData wsd;
    // 启动Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
    {
        cout << "WSAStartUp Error = " << WSAGetLastError() << endl;
        return -1;
    }
    else
    {
        cout << "WSAStartup Success" << endl;
    }
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); // 创建套接字
    if (sock == SOCKET_ERROR)
    {
        cout << "socket Error = " << WSAGetLastError() << endl;
        return -2;
    }
    else
    {
        cout << "socket Success" << endl;
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr(serverIp.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    string line;
    char buffer[NUM];
    while (1)
    {
        // 发送数据
        cout << "Please Enter#";
        getline(cin, line);
        int n = sendto(sock, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            cerr << "sendto Error" << endl;
            break;
        }
        cerr << "发送成功" << endl;
        // 接收数据
        buffer[0] = 0; // C式清空数组
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        int len = (int)sizeof(peer);
        n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "server 返回的消息是" << buffer << endl;
        }
        else
            break;
    }
    closesocket(sock); // 关闭套接字
    WSACleanup();
    return 0;
}